<!-- 训练 -->
<script lang="ts" setup>
import type { PageTableRequestData, TableItem } from "@@/apis/train/type.ts"
import type { FormInstance } from "element-plus"
import { getProjectId } from "@/common/utils/cache/local-storage"
import { parseSearchDate } from "@/common/utils/datetime"
import { deleteTaskApi, searchTaskApi } from "@@/apis/train"
import { usePagination } from "@@/composables/usePagination"
import { FormTypeEnum, taskStatusMap, taskStatusOptions } from "@@/constants/other-keys"
import { Refresh, Search } from "@element-plus/icons-vue"
import { ref, watch } from "vue"
import XEUtils from "xe-utils"
import { Card } from "./components"
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh"
import { isEmpty } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "TrainIndex"
})
let timer: number | null = null
const router = useRouter()
const isGrid = ref<boolean>(true)
const searchMore = ref<boolean>(false)
const searchFormRef = ref<FormInstance | null>(null)
const searchKey = ref()
const loading = ref<boolean>(false)
const tableData = ref<TableItem[]>([])
const multipleSelection = ref<TableItem[]>([])
const dialogType = ref<FormTypeEnum>(FormTypeEnum.VIEW)
const dialogVisible = ref<boolean>(false)
const curId = ref<string>()
const TableRef = ref()
const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
const searchData = reactive<PageTableRequestData>({
  task_name: undefined,
  task_tag: undefined,
  task_mode: "Train",
  project_id: getProjectId(),
  task_status: undefined,
  create_time: undefined,
  end_time: undefined,
  time_range: undefined,
  current_page: 0
})
function getTableData() {
  loading.value = true
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    task_mode: searchData.task_mode,
    task_name: undefined,
    task_tag: undefined,
    task_status: undefined,
    create_time: undefined,
    end_time: undefined,
    ...(!isEmpty(getProjectId()) ? { project_id: getProjectId() } : {}),
    ...(!isEmpty(searchKey.value) ? { search_key: searchKey.value } : {})
  }
  if (searchMore.value) {
    params.task_name = searchData.task_name
    params.task_status = searchData.task_status
    if (searchData.time_range && searchData.time_range.length == 2) {
      params.create_time = searchData.time_range[0]
      params.end_time = parseSearchDate(searchData.time_range[1])
    }
  }
  searchTaskApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function handleCreate() {
  router.replace({ name: "TrainCreate" })
}
function handleRowCurrentChange(val: TableItem | undefined) {
  if (val == undefined) {
    return
  }
  curId.value = val?.task_id
  dialogVisible.value = true
  dialogType.value = FormTypeEnum.VIEW
}
function handleSelectionChange(val: TableItem[]) {
  multipleSelection.value = val
}
function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item) => {
    ids.push(item.task_id as string)
    names.push(item.task_name)
  })
  ElMessageBox.confirm(`正在删除任务：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTaskApi({ task_ids: ids }).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}
function getRowKeys(row: TableItem) {
  return row.task_id
}
// #endregion
// #region 删
function handleDelete(row: TableItem) {
  ElMessageBox.confirm(`正在删除任务：${row.task_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    row.task_id
    && deleteTaskApi({ task_ids: [row.task_id] }).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
// #endregion
// #region 详情
function handleView(row: TableItem) {
  router.replace({ name: "MyProjectTrainView", query: { id: row.task_id } })
}
// #endregion

function handleToggleSelect(row: TableItem) {
  TableRef.value!.toggleRowSelection(row, undefined, false)
}
useAutoRefresh(getTableData)
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
onMounted(() => {
  getTableData()
  timer = Number(setInterval(getTableData, 1000 * 30))
})
onBeforeUnmount(() => {
  timer && clearInterval(timer)
})

const selectedId = computed(() => {
  if (multipleSelection.value !== undefined && multipleSelection.value.length > 0) {
    const ids = XEUtils.map(multipleSelection.value, (item) => {
      return item.task_id
    })
    return ids
  }
  return []
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item prop="task_name" label="任务名称">
            <el-input v-model="searchData.task_name" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="task_status" label="任务状态">
            <el-select
              v-model="searchData.task_status" placeholder="请选择" clearable style="width: 220px"
              @change="handleSearch()"
            >
              <el-option v-for="item in taskStatusOptions" :label="item.name" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker
              v-model="searchData.time_range" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="handleSearch()"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" v-throttle="() => resetSearch()">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreate">
            新建任务
          </el-button>
          <el-button
            :disabled="multipleSelection.length < 1" type="danger"
            @click="handleMultipleDelete"
          >
            批量删除
          </el-button>
        </div>
        <div class="flex-y-center sh-operate">
          <div class="sh-btn" :class="{ active: isGrid }" @click="() => isGrid = true">
            <el-tooltip content="卡片" placement="bottom">
              <SvgIcon name="table-grid" />
            </el-tooltip>
          </div>
          <div class="sh-btn" :class="{ active: !isGrid }" @click="() => isGrid = false">
            <el-tooltip content="列表" placement="bottom">
              <SvgIcon name="table-list" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-show="isGrid" class="cpi-content-main">
        <div class="custom-card-container">
          <template v-for="(item, index) in tableData" :key="index">
            <Card
              :data="item"
              :is-download="false"
              :selected="selectedId.includes(item.task_id as string)"
              @handle-delete="handleDelete"
              @handle-view="handleView"
              @toggle-select="handleToggleSelect"
            />
          </template>
        </div>
      </div>
      <div v-show="!isGrid" class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table
              ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
              :height="height" @current-change="handleRowCurrentChange" @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
              <el-table-column prop="task_name" label="任务名称" />
              <el-table-column prop="task_status" sortable label="运行状态">
                <template #default="{ row }">
                  <div class="status-tag" :class="`_${row.task_status}`">
                    {{ taskStatusMap[row.task_status] }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="task_describe" show-overflow-tooltip label="任务描述" />
              <el-table-column prop="create_user.user_name" sortable label="创建人" />
              <el-table-column prop="create_time" sortable label="创建时间" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop v-throttle="() => handleView(scope.row)" title="查看">
                      <el-icon :size="18">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger" @click.stop v-throttle="() => handleDelete(scope.row)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :disabled="loading"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.custom-card-container {
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  grid-auto-rows: 235px;
}

:deep(.el-table th.el-table__cell) {
  padding: 13px 0;
}

.status-tag {
  width: 75px;
  height: 32px;
  line-height: 32px;
  border: 1px solid rgb(31, 119, 222);
  text-align: center;
  border-radius: 5px;
}
._0 {
  color: rgb(31, 119, 222);
  background-color: rgba(27, 92, 149, 0.1);
  border-color: rgb(31, 119, 222);
}
._1 {
  color: rgb(255, 163, 24);
  background-color: rgba(219, 126, 16, 0.1);
  border-color: rgb(255, 163, 24);
}
._2 {
  color: rgb(0, 187, 153);
  border-color: rgb(0, 187, 153);
  background-color: rgba(0, 187, 153, 0.1);
}
._3 {
  color: rgb(245, 108, 108);
  border-color: rgb(245, 108, 108);
  background-color: rgba(211, 83, 72, 0.1);
}
._4 {
  color: rgb(96, 111, 145);
  border-color: rgb(96, 111, 145);
  background-color: rgba(83, 85, 97, 0.1);
}
</style>
